//
//  down.m
//  YiLiao
//
//  Created by mac on 16/7/5.
//  Copyright © 2016年 Noah. All rights reserved.
//

#import "down.h"
static NSUserDefaults *userDefaults;
static long long allLength;
static long long currentLength;


@implementation down
- (NSString *)getFileSize:(NSString *)name
{
    NSFileManager *manger = [NSFileManager defaultManager];
    NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/%@",name]];
    NSLog(@"%@",filePath);
    NSDictionary *infoDic = [manger attributesOfItemAtPath:filePath error:nil];
    //返回当前的文件大小
    return [[infoDic objectForKey:NSFileSize] stringValue];
    
}
-(void)getDownloadModel:(NSString *)str withName:(NSString *)nameStr withType:(UIButton *)button{
    NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/%@",nameStr]];
    
    NSFileManager *flieManager = [NSFileManager defaultManager];
    NSLog(@"%@",flieManager);
    if (![flieManager fileExistsAtPath:filePath]) {
        [flieManager createFileAtPath:filePath contents:nil attributes:nil];
    }
    NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:filePath];
    [handle seekToEndOfFile];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:str]];
    [request addValue:[NSString stringWithFormat:@"bytes=%@-",[self getFileSize:nameStr]] forHTTPHeaderField:@"Range"];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        [handle writeData:data];
        currentLength = [[self getFileSize:nameStr] longLongValue];
        allLength = response.expectedContentLength + currentLength;
        float prerent;
        if (currentLength == 0) {
            prerent = 0;
        }else{
            prerent = currentLength * 1.0/allLength;
        }
        [userDefaults setValue:[NSNumber numberWithFloat:prerent] forKey:@"length"];
        dispatch_sync(dispatch_get_main_queue(), ^{
            [self.delegate changView:prerent with:button];
        });
    }];
    
}
@end
